package com.wgj.android.http;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.jiaai.xui.XUI;
import com.jiaai.xui.utils.XAppUtils;
import com.jiaai.xui.utils.http.BaseHttpCallBack;
import com.jiaai.xui.utils.http.IHttpEngine;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.http.entity.VUpload;
import com.jiaai.xui.view.widget.XToast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

import static okhttp3.internal.Util.EMPTY_REQUEST;
/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/12/5
 * 描    述：
 * 修订历吏：
 * =========================================
 */
public class OKHttpEngine implements IHttpEngine {

    public OkHttpClient client = null;
    private int cacheSize = 10 * 1024 * 1024;
    public OKHttpEngine() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient().newBuilder()
                .retryOnConnectionFailure(true)
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .cache(new Cache(XUI.getContext().getCacheDir(), cacheSize))
                .addInterceptor(logging)
                .build();
    }

    @Override
    public void get(String url, Map<String, Object> params, final BaseHttpCallBack callBack) {
        Request request = new Request.Builder().url(url+getUrlParamsByMap(params)).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(0,e.toString(),false);

                    }
                });

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            callBack.onSuccess(response);
                        } catch (IOException e) {
                            callBack.onFailed(0,e.getMessage(),false);
                        }

                    }
                });
            }
        });
    }

    @Override
    public void post(String url, Map<String, Object> params, final BaseHttpCallBack callBack) {
        RequestBody body = EMPTY_REQUEST;
        if (null != params&&!params.isEmpty()) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (String key : params.keySet()) {
                Object value = params.get(key);
                try{ builder.addFormDataPart(key, value.toString()); }catch (Exception e){}

            }
            body = builder.build();
        }

        final Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(0,e.toString(),false);

                    }
                });

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            callBack.onSuccess(response);
                        } catch (IOException e) {
                            callBack.onFailed(0,e.getMessage(),false);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void get(String s, String s1, Map<String, Object> map, BaseHttpCallBack httpCallBack) {

    }

    @Override
    public  void upload(String directories,Map<String,File> files,final ListHttpCallBack<VUpload> callBack){
        RequestBody body = EMPTY_REQUEST;
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String key:files.keySet()){
            File file=files.get(key);
            /*builder.addFormDataPart(key, file.getName(),
                    RequestBody.create(MediaType.parse("multipart/form-data"), file));//"application/octet-stream"*/
            builder.addFormDataPart(key, file.getName(),
                    RequestBody.create(MediaType.parse("image/png"), file));//"application/octet-stream"
        }
        body = builder.build();
        String str = XAppUtils.readMetaDataFromApplication("uploadUrl")+"/"+directories;
        final Request request = new Request.Builder()
                .url(XAppUtils.readMetaDataFromApplication("uploadUrl")+"/"+directories)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailed(0,e.toString(),false);
                        XToast.error("上传失败");
                    }
                });

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
               final String s=response.body().string();
                XHttp.handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ArrayList<VUpload> datas=new ArrayList<>();
                        if(s.indexOf("[")==0){
                                  //Gson gson=new Gson();
                                    //JsonArray arrar= new JsonParser().parse(s).getAsJsonArray();

                            try {
                                JSONArray array = new JSONArray(s);
                                for(int i=0;i<array.length();i++){
                                    VUpload vUpload = new VUpload();

                                    vUpload.setFilePath(array.getString(0));
                                    datas.add(vUpload);
                                    //datas.add(gson.fromJson(arrar.get(i),VUpload.class));

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }else {
                            String paths=s;

                            if(paths.lastIndexOf(",")==paths.length()-1){
                                paths=paths.substring(0,paths.length()-1);
                            }
                            for(String s:paths.split(",")){
                                VUpload vUpload = new VUpload();
                                vUpload.setFilePath(s);
                                datas.add(vUpload);

                            }
                        }

                        callBack.onSuccess(datas);
                     }
                });


            }
        });

    }

    //下载文件方法
    public static void downloadFile(String url, final ProgressListener listener, Callback callback){
        OkHttpClient clients=  new OkHttpClient().newBuilder()
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());
                        return response.newBuilder().body(new ProgressResponseBody(response.body(),listener)).build();
                    }
                })
                .build();
        Request request = new Request.Builder().url(url).build();
        clients.newCall(request).enqueue(callback);
    }

    private String getUrlParamsByMap(Map<String, Object> map) {
        if (map == null||map.isEmpty()) {
            return "";
        }
        StringBuffer params = new StringBuffer("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.append(entry.getKey());
            params.append("=");
            params.append(entry.getValue());
            params.append("&");
        }
        String str=params.toString();
        return str.substring(0,str.length()-1);
    }

    public interface ProgressListener {
        //已完成的 总的文件长度 是否完成
        void onProgress(long currentBytes, long contentLength, boolean done);
    }

}